package com.gogant.spider.core;

import com.gogant.spider.util.StringUtils;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

public final class Context {
    private URL url;
    private int maxDepth;
    private int priority;
    private long expire;
    private List<URLHandler<?, ?>> handlerList;

    public Context(URL url) {
        this.url = url;
    }

    /**
     * 获取URL
     *
     * @return
     */
    public URL getURL() {
        return url;
    }

    /**
     * 设置爬取深度
     *
     * @param maxDepth
     */
    public void setMaxDepth(int maxDepth) {
        this.maxDepth = maxDepth;
    }

    /**
     * 获取爬取深度
     *
     * @return
     */
    public int getMaxDepth() {
        return maxDepth;
    }

    /**
     * 获取优先级
     *
     * @return
     */
    public int getPriority() {
        return priority;
    }

    /**
     * 设置优先级
     *
     * @param priority
     */
    public void setPriority(int priority) {
        this.priority = priority;
    }

    /**
     * 获取URL缓存时间
     *
     * @return
     */
    public long getExpire() {
        return expire;
    }

    /**
     * 设置URL缓存时间
     *
     * @param expire
     */
    public void setExpire(long expire) {
        this.expire = expire;
    }

    /**
     * 添加URLHandler
     *
     * @param handler
     */
    protected void addHandler(URLHandler<?, ?> handler) {
        if (handlerList == null) {
            handlerList = new ArrayList<URLHandler<?, ?>>();
        }
        handlerList.add(handler);
    }

    /**
     * 检查context中是否包含URLHandler
     *
     * @return
     */
    protected boolean hasHandler() {
        return handlerList != null && handlerList.size() > 0;
    }

    /**
     * 获取URLHandler列表
     *
     * @return
     */
    protected List<URLHandler<?, ?>> getHandlerList() {
        return handlerList;
    }

    /**
     * 检测URL是否满足此正则表达式L
     *
     * @param regex
     * @return
     */
    public boolean matches(String regex) {
        return Pattern.matches(regex, url.toString());
    }

    /**
     * 检测URL是否满足此正则表达式
     *
     * @param regex
     * @return
     */
    public boolean find(String regex) {
        return Pattern.compile(regex).matcher(url.toString()).find();
    }

    /**
     * 检测URL是否满足此表达式，表达式格式类似SQL中的like
     *
     * @param exp
     * @return
     */
    public boolean like(String exp) {
        return StringUtils.isLike(url.toString(), exp);
    }
}
